from wxpy import *
import os
import time


def weixin_file_path():
    avater_dir = os.path.join(os.getcwd(), 'weixin')
    if not os.path.exists(avater_dir):
        os.mkdir(avater_dir)
    return avater_dir


def save_wx_avater(avater_dir):
    bot = Bot(cache_path=False)
    friends = bot.friends(update=True)
    list_name = []
    for friend in friends:
        try:
            friend.get_avatar(os.path.join(avater_dir, f'{str(friend.name)}.jpg'))
            list_name.append(friend.name)
            time.sleep(0.3)
            print("好友昵称：%s" % friend.name)
        except Exception as e:
            print("数据错误",e)
            pass
    with open('微信好友昵称.txt', 'w+', encoding='utf-8')as f:
        for n in list_name:
            f.write("'" + n + "',\n")
        f.close()
        print("程序结束：")
    print(list_name)


if __name__ == '__main__':
    avatar_dir = weixin_file_path()
    save_wx_avater(avatar_dir)